package com.resou.reader.choosegender.giftbook;

import android.os.Message;
import android.util.Log;

import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.LargessBook;
import com.resou.reader.api.service.GenderService;
import com.resou.reader.base.ResouBasePresenter;
import com.resou.reader.bookshelf.readhistory.datasupport.BookCollection;
import com.resou.reader.data.Injection;
import com.resou.reader.data.bookshelf.BookshelfRepository;
import com.resou.reader.data.local.LitePalHelper;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.utils.AppExecutors;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.eventbus.LoadBookEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;

public class GiftBooksPresenter extends ResouBasePresenter<GiftBooksContract.View> implements GiftBooksContract.Presenter {

    private final GenderService mService;
    private BookshelfRepository mRepository;

    public GiftBooksPresenter(GiftBooksContract.View view) {
        super(view);
        mService = ApiImp.getInstance().getService(GenderService.class);
        mRepository = Injection.provideBookshelfRepository();

    }

    private static final String TAG = "GiftBooksPresenter-App";

    @Override
    public void loadBooks(String gender, String categoriesStr) {
        addCompositeDisposable(
                mService.getLargessBooks(gender, categoriesStr)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(resultList -> {
                            if (resultList.getCode() == 0) {
                                List<LargessBook> data = resultList.getData();
                                mView.setBooks(data);
                            } else {
                                ToastUtil.makeShortToast(resultList.getMsg());
                            }
                        }, throwable -> {
                            mView.showError(throwable);
                        })
        );
    }

    @Override
    public void skipChoose(String gender, String categoriesStr) {
        addCompositeDisposable(
                mService.getLargessBooks(gender, categoriesStr)
                        .subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.io())
                        .subscribe(resultList -> {
                            if (resultList.getCode() == 0) {
                                List<LargessBook> data = resultList.getData();
                                //保存书籍到数据库
                                saveFreeBooks(data);
                            }
                            // ToastUtil.makeShortToast(resultList.getMsg());

                        }, throwable -> {
//                            mView.showError(throwable);
                        })
        );
    }

    @Override
    public void save(List<LargessBook> largessBooks) {
        AppExecutors.getAppExecutors().diskIO().execute(() -> saveFreeBooks(largessBooks));
    }

    /**
     * 保存服务器送的免费书
     *
     * @param largessBooks
     */
    private void saveFreeBooks(List<LargessBook> largessBooks) {
        LitePalHelper.saveLargessBooks(largessBooks);
        EventBus.getDefault().post(new Message());
        EventBus.getDefault().post(new LoadBookEvent());
    }

    /**
     * 异步同步书籍
     *
     * @param bookIdStr
     */
    public synchronized void synchronizeBooks(String bookIdStr) {

        mRepository.synchronizeBooks(UserInstance.getToken(), bookIdStr, "android")
                .subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers())
                .subscribe(new DefaultObserver<List<BookCollection>>() {
                    @Override
                    public void onNext(List<BookCollection> bookCollections) {
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "onError: " + e.getMessage());
                        mView.showError(e);
                        mView.finishPage();
                    }

                    @Override
                    public void onComplete() {
                        mView.finishPage();
                    }
                });
    }

}
